"""
入口文件
"""

import os

from flask import Flask
from flask_cors import CORS
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
from flask_uploads import configure_uploads
from common.res import res
from config import config, UploadConfig
from models import db
from router import Router

# 读取环境信息
env = os.getenv("FLASK_ENV", "dev")
print(f"环境变量 {env}")


app = Flask(__name__)

# 开启跨域
CORS(app)

# jwt验证
jwt = JWTManager(app)

# 根据环境变量加载配置项
app.config.from_object(config[env])

# 初始化数据库
db.init_app(app)
# 初始化数据库ORM迁移插件
migrate = Migrate()
migrate.init_app(app, db)

# 注册蓝图
app.register_blueprint(Router.user)
app.register_blueprint(Router.file)

# 上传配置
configure_uploads(app, [UploadConfig.avatar])


@jwt.invalid_token_loader
def invalid_token_callback(error):
    """无效token"""
    print(f"无效token{error}")
    return res(code=401)


@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
    """过期token"""
    print(f"token过期{jwt_header}{jwt_payload}")
    return res(code=401)


# @jwt.token_verification_failed_loader
# def token_verification_failed(callback):
#     """token验证失败"""
#     return res(code=401, message="无效token")


# 创建表
with app.app_context():
    db.create_all()

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5001, debug=False)
